import 'package:hinge/common/index.dart';

class UserService {
  static const String userListKey = 'user_list';
  static const String currentUserKey = 'current_user';
  static const String guestUserKey = 'guest_user';
  static const int guestUserId = 999; // 设置游客特定ID

  /// 初始化七个默认用户（英文昵称，5-6字母）
  static Future<void> initDefaultUsers() async {
    List<UserModel> users = [
      UserModel(
        id: 1,
        account: 'user1',
        password: '123456',
        nickname: 'Aurora',
        avatar: 'assets/images/avatar1.png',
        description:
            'I love floral and fruity scents that remind me of spring mornings.',
      ),
      UserModel(
        id: 2,
        account: 'user2',
        password: '123456',
        nickname: 'Bella',
        avatar: 'assets/images/avatar2.png',
        description:
            'Woody and amber notes are my signature. Strong and sophisticated.',
      ),
      UserModel(
        id: 3,
        account: 'user3',
        password: '123456',
        nickname: 'Clara',
        avatar: 'assets/images/avatar3.png',
        description:
            'Fresh and aquatic fragrances take me back to my coastal hometown.',
      ),
      UserModel(
        id: 4,
        account: 'user4',
        password: '123456',
        nickname: 'Diana',
        avatar: 'assets/images/avatar4.png',
        description:
            'Oriental spices and vanilla make the perfect combination for my taste.',
      ),
      UserModel(
        id: 5,
        account: 'user5',
        password: '123456',
        nickname: 'Emma',
        avatar: 'assets/images/avatar5.png',
        description:
            'Citrus scents energize my day. Bergamot is my absolute favorite note.',
      ),
      UserModel(
        id: 6,
        account: 'user6',
        password: '123456',
        nickname: 'Felix',
        avatar: 'assets/images/avatar6.png',
        description:
            'I collect vintage fragrances and enjoy the history behind each bottle.',
      ),
      UserModel(
        id: 7,
        account: 'user7',
        password: '123456',
        nickname: 'Grace',
        avatar: 'assets/images/avatar7.png',
        description:
            'Rose and jasmine - the timeless classics never disappoint me.',
      ),
    ];
    await SpUtil.setModelList(
      userListKey,
      users.map((e) => e.toJson()).toList(),
    );
  }

  /// 获取所有用户
  static List<UserModel> getAllUsers() {
    return SpUtil.getModelList(userListKey, (json) => UserModel.fromJson(json));
  }

  /// 根据账号查找用户
  static UserModel? getUserByAccount(String account) {
    try {
      return getAllUsers().firstWhere((u) => u.account == account);
    } catch (e) {
      return null;
    }
  }

  /// 新增用户
  static Future<void> addUser(UserModel user) async {
    List<UserModel> users = getAllUsers();
    users.add(user);
    await SpUtil.setModelList(
      userListKey,
      users.map((e) => e.toJson()).toList(),
    );
  }

  /// 登录方法，返回用户对象或null
  static UserModel? login(String account, String password) {
    try {
      return getAllUsers().firstWhere(
        (u) => u.account == account && u.password == password,
      );
    } catch (e) {
      return null;
    }
  }

  /// 注册方法，返回注册成功的用户对象或null（账号已存在返回null）
  static Future<UserModel?> register(String account, String password) async {
    if (getUserByAccount(account) != null) {
      // 账号已存在
      return null;
    }
    List<UserModel> users = getAllUsers();
    int newId =
        users.isNotEmpty
            ? users.map((e) => e.id).reduce((a, b) => a > b ? a : b) + 1
            : 1;
    String nickname = 'User$newId';
    String avatar = 'assets/images/avatar1.png';
    UserModel user = UserModel(
      id: newId,
      account: account,
      password: password,
      nickname: nickname,
      avatar: avatar,
      description:
          'Scent is a language that allows me to be understood without having to speak.',
    );
    await addUser(user);
    return user;
  }

  /// 修改用户信息（根据id），可选参数
  static Future<bool> updateUser({
    required int id,
    String? nickname,
    String? password,
    String? avatar,
    String? description,
  }) async {
    List<UserModel> users = getAllUsers();
    int idx = users.indexWhere((u) => u.id == id);
    if (idx == -1) return false;
    UserModel old = users[idx];
    users[idx] = UserModel(
      id: old.id,
      account: old.account,
      password: password ?? old.password,
      nickname: nickname ?? old.nickname,
      avatar: avatar ?? old.avatar,
      description: description ?? old.description,
    );
    await SpUtil.setModelList(
      userListKey,
      users.map((e) => e.toJson()).toList(),
    );
    return true;
  }

  /// 删除账号（根据id）
  static Future<bool> deleteUser(int id) async {
    List<UserModel> users = getAllUsers();
    int before = users.length;
    users.removeWhere((u) => u.id == id);
    await SpUtil.setModelList(
      userListKey,
      users.map((e) => e.toJson()).toList(),
    );
    return users.length < before;
  }

  static UserModel? getUserById(int id) {
    // 这个方法会被Observer监听，所以每次返回新的实例以确保能触发更新
    final users = getAllUsers();
    try {
      return users.firstWhere((u) => u.id == id);
    } catch (e) {
      // 找不到用户时返回第一个用户或null
      return users.isNotEmpty ? users.first : null;
    }
  }

  /// 创建游客账号
  static Future<UserModel> createGuestUser() async {
    UserModel guestUser = UserModel(
      id: guestUserId,
      account: 'guest',
      password: '',
      nickname: 'Guest',
      avatar: 'assets/images/avatar5.png',
      description: 'Welcome to explore the fragrance world as a guest!',
    );

    // 保存游客信息
    await SpUtil.setModel(guestUserKey, guestUser.toJson());

    // 设置当前用户为游客
    await setCurrentUser(guestUser);

    return guestUser;
  }

  /// 检查是否为游客状态
  static bool isGuestUser() {
    UserModel? currentUser = getCurrentUser();
    return currentUser?.id == guestUserId;
  }

  /// 获取当前登录用户
  static UserModel? getCurrentUser() {
    try {
      // 每次都强制从SharedPreferences读取，避免缓存问题
      final user = SpUtil.getModel(
        currentUserKey,
        (json) => UserModel.fromJson(json),
      );
      return user;
    } catch (e) {
      print('Error getting current user: $e');
      return null;
    }
  }

  /// 设置当前登录用户
  static Future<void> setCurrentUser(UserModel user) async {
    await SpUtil.setModel(currentUserKey, user.toJson());
  }

  /// 自动游客登录，如果已有登录用户则返回该用户，否则创建游客账号
  static Future<UserModel> autoGuestLogin() async {
    UserModel? currentUser = getCurrentUser();
    if (currentUser != null) {
      return currentUser;
    }
    return await createGuestUser();
  }

  /// 退出登录
  static Future<void> logout() async {
    await SpUtil.remove(currentUserKey);
  }

  /// 从游客账号转为正式账号
  static Future<UserModel?> convertFromGuest(
    String account,
    String password,
    String nickname,
  ) async {
    if (getUserByAccount(account) != null) {
      // 账号已存在
      return null;
    }

    // 创建新账号
    List<UserModel> users = getAllUsers();
    int newId =
        users.isNotEmpty
            ? users.map((e) => e.id).reduce((a, b) => a > b ? a : b) + 1
            : 1;

    UserModel user = UserModel(
      id: newId,
      account: account,
      password: password,
      nickname: nickname,
      avatar: 'assets/images/avatar1.png',
      description:
          'Scent is a language that allows me to be understood without having to speak.',
    );

    await addUser(user);
    await setCurrentUser(user);

    // 清除游客信息
    await SpUtil.remove(guestUserKey);

    return user;
  }
}
